# coding: utf-8

import os
from web import form
import httplib
import urllib
from config import DIR


def get_avatar_dir():
    partdir = os.path.dirname(__file__)
    partdir = os.path.dirname(partdir)
    partdir = os.path.dirname(partdir)
    return os.path.normpath(os.path.join(partdir, DIR.avatar))

def verify_dir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

def hash_path(id):
    path = ''

    while True:
        tmp = id % 1024
        path = '%d/%s' % (tmp, path)
        id = id / 1024
        if id == 0:
            break
    
    return os.path.normpath(path)

def google_location(query):
    query = query.encode('utf-8')
    query_server = "/maps/geo?q=%s&output=csv"
    query = query_server % '+'.join(query.split())
    conn = httplib.HTTPConnection("ditu.google.com")
    conn.request("GET", query)
    resp = conn.getresponse()
    data = resp.read()
    stat, acc, x, y = data.split(',')
    if stat == "200":
        return (int(acc), float(x), float(y))
    else:
        raise ValueError

def recover_datetime(acts):
    tmp = []
    for act in acts:
        act['gathertime'] = act['gathertime'].strftime(
                "%m月%d日 %H:%M")
        act['startime'] = act['startime'].strftime(
                "%m月%d日 %H:%M")
        tmp.append(act)
    return tmp

def page_split_up(length, offset, limit, pages):
    more_front = False
    more_end = False
    current_page = 0
    start_page = 0
    end_page = 0
    end_offset = 0

    current_page = offset / limit + 1
    total_pages = length / limit
    end_offset = total_pages

    if current_page - pages < 0: # 1 2 '3' 4 5 6 more
        start_page = 0
        end_page = pages
        more_front = False
        more_end = True
    else:
        if current_page + pages > total_pages: # more 32 33 '34' 35 36
            start_page = total_pages - pages
            end_page = total_pages
            more_front = True
            more_end = False
        else:                # more 22 23 '24' 25 26  more
            start_page = current_page - pages / 2
            end_page = current_page + pages / 2
            more_front = True
            more_end = True

    if total_pages <= pages:
        more_front = False
        more_end = False
        end_page = total_pages

    spval= (more_front, more_end, current_page, start_page, end_page, end_offset)
    spkey = ("more_front", "more_end", "current_page", "start_page", "end_page", "end_offset")

    return dict(zip(spkey, spval))
            

vemail = form.regexp(r"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "必须为有效Email地址")
vpass = form.regexp(r"\w{6,20}$", '请输入6-20长度的字母，数字，下划线')
vreg = form.regexp(r"\w{1,32}$", '不能为空')
vnum = form.regexp(r"\d+", '请输入数字')
vsearch = form.regexp(r"\w{2,32}$", '请输入2-32长度的字母，数字，下划线')

LOCATION = ['北京', '天津', '上海', '广州', '成都', '其他']

NEED_LOGIN_URLS = ['setting', 'avatar', 'passwd', 'logout',
        'news', 'map', 'profile', 'activity', 'users', 'acts', 'act_add', 'act_admin',
        'discuss_create', 'discuss_show', 'discuss_op']

ACTYPE = ['轮滑', '骑行', '腐败', '游泳']
OURS = ['07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', 
        '19', '20', '21', '22', '23', '24', '01', '02', '03', '04', '05', '06']

MINS = ['05', '10', '15', '20', '25', '30', 
       '35', '40', '45', '50', '55', '00']

AREA = ['朝阳', '宣武', '东城', '西城', '丰台', '海淀', '崇文',
        '石景山', '门头沟', '房山', '通州', '顺义', '昌平', '大兴',
        '怀柔', '平谷', '密云', '延庆']

RELATION={'wish':0, 'do':1, 'cancel':2}

NEWS={'newuser': 0,   # 新用户
      'avatar': 1,    # 上传头像
      'newact': 2,    # 新活动
      'relation': 3,  # 用户对活动的操作
      'newthread': 4, # 发表新主题
      'newpost': 5,   # 发表新回复
      'say': 6,       # 发表广播
      'picture': 7,   # 上传图片
      }

TINY_AVATAR_SIZE = (48, 48)
